<script setup>
import { ref, onMounted } from "vue";
import { listMyJoinProject } from "@/api/project.js";

// 数据
const ongoingProjects = ref([]);
const loading = ref(false);
const error = ref(null);

import { useUserStore } from '@/stores/user'
import routes from "@/router/index.js";
const userStore = useUserStore()


const userId = userStore.userDetails.userId;

// 获取进行中项目
const fetchOngoingProjects = async () => {
  loading.value = true;
  try {
    const response = await listMyJoinProject(userId, 1);
    if (response.data.code === 200) {
      ongoingProjects.value = response.data.data;
    } else {
      throw new Error(response.data.msg || "获取数据失败");
    }
  } catch (err) {
    error.value = err.message || "请求失败";
  } finally {
    loading.value = false;
  }
};
const goToDetailPage = (productId) => {
  routes.push({path: '/project-details', query: {productId}});
};
// 初始化加载
onMounted(fetchOngoingProjects);
</script>

<template>
  <div>
    <h1 style="text-align: center; margin-top: 20px;">已加入的项目</h1>

    <!-- 错误提示 -->
    <el-alert v-if="error" type="error" :closable="false" title="获取数据失败"/>

    <!-- 项目列表 -->
    <el-table v-if="!loading" :data="ongoingProjects" border style="width: 100%;margin-top: 20px;">
      <el-table-column prop="projectName" label="项目名称" width="200" />
      <el-table-column label="项目图片" width="150">
        <template #default="{ row }">
          <img :src="row.image" alt="项目图片" class="table-image" />
        </template>
      </el-table-column>
      <el-table-column prop="lab" label="实验室" width="150" />
      <!--      指导老师 -->
      <el-table-column prop="teacherName" label="指导老师" width="100" />
      <!--      负责人-->
      <el-table-column prop="userName" label="负责人" width="100" />
      <!--      开始时间 {{ new Date(pendingProjects.startTime).toLocaleDateString() }} -->
      <el-table-column label="开始时间" width="100">
        <template #default="{ row }">
          <el-button type="text" @click="() => {}">
            {{ new Date(row.startTime).toLocaleDateString() }}
          </el-button>
        </template>
      </el-table-column>
      <!--      结束时间 -->
      <el-table-column label="结束时间" width="100">
        <template #default="{ row }">
          <el-button type="text" @click="() => {}">
            {{ new Date(row.endTime).toLocaleDateString() }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button type="success" @click=" goToDetailPage(row.id)">
           查看详情
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 加载中 -->
    <el-skeleton v-else animated :rows="5"/>
  </div>
</template>

<style scoped>
.table-image {
  width: 100%;
  max-height: 100px;
  object-fit: contain;
  border-radius: 8px;
}
</style>
